import React from 'react'

// 引入官方的地区数据
import { areaList } from '@vant/area-data'

const Profile = () => {

    // 获取cookie
    let Cookie = JSON.stringify(React.$Cookies.load('LoginUser',{path:'/'})) !== '{}' ? JSON.parse(React.$Cookies.load('LoginUser',{path:'/'})) : {}

    // 设置状态数据
    const [LoginUser, SetLoginUser] = React.useState(Cookie)

    // 钩子函数初始化路由跳转对象
    const navigate = React.$Router.useNavigate()

    // 初始化表单元素
    const [form] = React.$Vant.Form.useForm()

    // 头像
    const Avatar = () => {
        if (LoginUser.avatar) {
            return (
                <img src={LoginUser.avatar_cdn} alt="" />
            )
        } else {
            return (
                <img src="/assets/images/toux.jpg" alt="" />
            )
        }
    }

    // 头像状态
    const [avatar, SetAvatar] = React.useState([
        { url: LoginUser.avatar_cdn }
    ])

    // 昵称，手机号
    const NickName = () => {
        if (LoginUser.nickname) {
            return (
                <h2>{LoginUser.nickname}</h2>
            )
        } else if (LoginUser.mobile) {
            return (
                <h2>{LoginUser.mobile_text}</h2>
            )
        } else {
            return (
                <h2>请先登录</h2>
            )
        }
    }

    // 性别
    const [GenderShow, SetGenderShow] = React.useState(false)
    const GenderList = [
        { text: '保密', value: 0 },
        { text: '男', value: 1 },
        { text: '女', value: 2 },
    ]

    const GenderConfirm = (_,gender) => {

        if(!gender)
        {
            return false
        }

        // 隐藏picker
        SetGenderShow(false)
        
        LoginUser.gender = gender.value
        LoginUser.sex_text = gender.text

        SetLoginUser(LoginUser)
    }

    //地区
    const [RegionShow, SetRegionShow] = React.useState(false)
    const [region, SetRegion] = React.useState('')
    const [code, SetCode] = React.useState([])


    const RegionInit = () => {
        var RegionStr = ''
        var RegionCode = []
        

        if(LoginUser.region)
        {
            RegionStr = LoginUser.region

            RegionCode.push(LoginUser.province)
            RegionCode.push(LoginUser.city)
            RegionCode.push(LoginUser.district)
        }

        SetRegion(RegionStr)
        SetCode(RegionCode)
    }

    const RegionConfirm = (_,result) => {
        SetRegionShow(false)

        var [province, city, district] = result

        let RegionStr = ''

        if(province)
        {
            RegionStr = province.text + '-'
            LoginUser.province = province.value
        }

        if(city)
        {
            RegionStr += city.text + '-'
            LoginUser.city = city.value
        }

        if(district)
        {
            RegionStr += district.text
            LoginUser.district = district.value
        }

        LoginUser.region = RegionStr

        SetLoginUser(LoginUser)

        RegionInit()
    }

    // 返回
    const back = () => {
        navigate(-1)
    }

    const onProfile = async (values) => {
        // 封装数据
        let data = {
            id:LoginUser.id,
            email:values.email,
            mobile:values.mobile,
            nickname:values.nickname,
            gender:LoginUser.gender,
            province:LoginUser.province,
            city:LoginUser.city,
            district:LoginUser.district
        }

        // 更新密码
        if(values.password)
        {
            data.password = values.password
        }

        // 测试邮箱 3436589094

        let avatar = values.avatar[0].file ? values.avatar[0].file : {}

        if(avatar || JSON.stringify(avatar) !== '{}')
        {
            data.avatar = avatar
        }

        // 发起请求
        let result = await React.$Api.profile(data)
    
        if(result.code === 1)
        {
            React.$Vant.Notify.show({
                type:'success',
                message:result.msg,
                onClose:() => {
                    React.$Cookies.save('LoginUser',result.data,{path:'/'})
                    React.$LoginUser = result.data

                    navigate('/user/base/index')
                }
            })
        }else{
            React.$Vant.Notify.show({
                type: 'warning',
                message: result.msg
            })
        }

    }

    React.useEffect(() => {
        RegionInit()
    },[])

    return (
        <>
            <div className="my_kuang">
                {/* 顶部导航 */}
                <React.$Vant.Sticky>
                    <React.$Vant.NavBar
                        title="个人资料"
                        onClickLeft={back}
                        zIndex="10"
                    />
                </React.$Vant.Sticky>

                <div className="bj_img">
                    <img className="beij_s" src="/assets/images/my_beij.jpg" alt="" />
                    <div className="nimetou_gaib">
                        <div className="toux_hou">
                            <Avatar />
                        </div>
                        <div className="mingz">
                            <NickName />
                        </div>
                    </div>
                </div>

                {/* 表单 */}
                <React.$Vant.Form form={form} onFinish={onProfile}>
                    {/* 手机号 */}
                    <React.$Vant.Form.Item
                        labelWidth='3.5em'
                        labelAlign='right'
                        name='mobile'
                        label='手机号'
                        initialValue={LoginUser.mobile}
                        colon
                    >
                        <React.$Vant.Input placeholder='请输入手机号' disabled />
                    </React.$Vant.Form.Item>

                    {/* 昵称 */}
                    <React.$Vant.Form.Item
                        labelWidth='3.5em'
                        labelAlign='right'
                        name='nickname'
                        label='昵称'
                        initialValue={LoginUser.nickname}
                        colon
                        rules={[
                            {required:true, message: '请输入昵称'}
                        ]}
                    >
                        <React.$Vant.Input placeholder='请输入昵称'  />
                    </React.$Vant.Form.Item>

                    {/* 邮箱 */}
                    <React.$Vant.Form.Item
                        labelWidth='3.5em'
                        labelAlign='right'
                        name='email'
                        label='邮箱'
                        initialValue={LoginUser.email || ''}
                        colon
                        rules={[
                            {required:true, message: '请输入邮箱'},
                            {type:'email', message: '请输入正确的邮箱格式'}
                        ]}
                    >
                        <React.$Vant.Input placeholder='请输入邮箱'  />
                    </React.$Vant.Form.Item>

                    {/* 密码 */}
                    <React.$Vant.Form.Item
                        labelWidth='3.5em'
                        labelAlign='right'
                        name="password"
                        label="密码"
                        colon
                    >
                        <React.$Vant.Input placeholder="留空，不需要密码" type="password" />
                    </React.$Vant.Form.Item>

                    {/* 性别 */}
                    <React.$Vant.Form.Item
                        label="性别"
                        labelWidth='3.5em'
                        labelAlign='right'
                        onClick={() => {SetGenderShow(true)}}
                        colon
                        isLink
                    >
                        <React.$Vant.Input placeholder="请选择性别" readonly value={LoginUser.sex_text} />
                    </React.$Vant.Form.Item>

                    <React.$Vant.Popup position="bottom" round visible={GenderShow} onClose={() => {SetGenderShow(false)}}>
                        <React.$Vant.Picker 
                            title="性别" 
                            columns={GenderList} 
                            defaultIndex={LoginUser.gender}
                            onConfirm={GenderConfirm} 
                            onCancel={() => {SetGenderShow(false)}}
                        />
                    </React.$Vant.Popup>

                    {/* 地区 */}
                    <React.$Vant.Form.Item
                        labelWidth='3.5em'
                        labelAlign='right'
                        label="地区"
                        onClick={() => {SetRegionShow(true)}}
                        colon
                        isLink
                    >
                        <React.$Vant.Input placeholder="请选择地区" readonly value={region} />
                    </React.$Vant.Form.Item>

                    <React.$Vant.Popup 
                        position="bottom"
                        visible={RegionShow}
                        onClose={() => {SetRegionShow(false)}}
                        round
                    >
                        <React.$Vant.Area 
                            title="选择地区"
                            value={code}
                            areaList={areaList} 
                            onConfirm={RegionConfirm}
                            onCancel={() => SetRegionShow(false)}
                        />
                    </React.$Vant.Popup>

                    {/* 头像 */}
                    <React.$Vant.Form.Item
                        label="头像"
                        name="avatar"
                        initialValue={[
                        {url: LoginUser.avatar_cdn}
                        ]}
                        labelWidth='3.5em'
                        labelAlign='right'
                        colon
                    >
                        <React.$Vant.Uploader maxCount={1} value={avatar}  />
                    </React.$Vant.Form.Item>

                    <div style={{width:'50%',textAlign:'center',margin:'10px auto 10px',paddingBottom:'10px'}}>
                        <React.$Vant.Button nativeType="submit" block size="normal" type="primary" round>修改资料</React.$Vant.Button>
                    </div>

                </React.$Vant.Form>
            </div>
        </>
    )
}

export default Profile